$(function () {
    var MASK = [];
    (function () {
        function to_ip (n) {
            var a = [];
            a[0] = (n >> 24) & 0xff;
            a[1] = (n >> 16) & 0xff;
            a[2] = (n >>  8) & 0xff;
            a[3] =  n        & 0xff;
            return a.join ('.');
        }
        var n = 0xffffffff, i;
        for (i = 0; i <= 32; i ++) {
            MASK [32 - i] = to_ip (n);
            n = (n << 1) & 0xffffffff;
        }
    })();
    function check_mqtt_status () {
        var checked = this.checked, keys = $('li[data-parent="mqtt"] .sys-param-key');
        $('li[data-parent="mqtt"] input').prop ('disabled', !this.checked);
        if (checked) {
            keys.removeClass ('disabled');
        } else {
            keys.addClass ('disabled');
        }
    }
    $('a[data-role="lock"]').on('click', function () {
        var name = $(this).attr ('data-group');
        var lock= $(this).find('i'), sub=$('input[name="'+name+'"]');
        if(lock.hasClass('fa-lock')){
            lock.removeClass('fa-lock').addClass('fa-unlock');
            sub.removeAttr("readonly");
        }else {
            lock.removeClass('fa-unlock').addClass('fa-lock');
            sub.attr("readonly",true);
        }
    });
    function check_login_items () {
        var type = this.value, title = panel.find ('.op-row');
        if (type === 'N') {
            panel.hide ();
            return;
        }

        panel.show ();
        if (type === 'B') {
            title.removeClass ('bg-success').addClass ('bg-danger');
            title.find ('.text-success').hide ();
            title.find ('.text-danger').show ();
        } else {
            title.removeClass ('bg-danger').addClass ('bg-success');
            title.find ('.text-danger').hide ();
            title.find ('.text-success').show ();
        }
        fetch_block_items (type)
    }
    function fetch_block_items (type) {
        list.empty ();
        Libs.ajax ({url:'ms/block-items?type=' + type}, function (response) {
            response = response.data;
            console.log (response);
            if (response.length) {
                for (var i = 0; i < response.length; i ++) {
                    append_item (response [i]);
                }
            }
        });
    }
    function append_item (data) {
        var li = $('<li/>').attr ('data-id', data['id']).appendTo (list);
        var a = $('<a class="list-item"/>').appendTo (li);
        $('<span class="ip-name"/>').text (data['memo']).appendTo (a);
        $('<span class="ip-addr"/>').text (data['ip']).appendTo (a);
        $('<span class="subnet"/>').text (data['mask']).appendTo (a);
        if (data['id'] !== 'localhost')
        $('<span class="pull-right hover-button"/>')
            .on ('click', delete_item)
            .append ('<i class="fa fa-fw fa-close"></i>').appendTo (a);
    }
    function delete_item () {
        var li = $(this).closest ('li');
        $.Alert.prompt (RS(R,'system.config.delete-info'), function () {
            Libs.ajax ({url:'ms/block-item?id=' + li.attr ('data-id'), type:'delete'}, function () {
                li.remove ();
            });
        });
    }
    function close_editor () {
        editor.appendTo (holder);
        $('.editor-row input').val ('');
    }
    function cancel_edit () {
        $.Alert.warn (RS(R,'system.config.edit-info')+'<div class="dlg-hint danger-hint">'+RS(R,'system.config.cancel-edit')+'</div>', function () {
            close_editor ();
        });
    }
    function accept_edit () {
        if (check_item_edit()) {
            // ip, mask, type
            var data = {
                ip:$.trim (ip_addr.val ()),
                mask:$.trim (subnet.val ()),
                type:login_type.val (),
                memo:$.trim (memo.val ())
            };
            $('#btn-confirm-item').hide();
            Libs.ajax ({url :'ms/save-block-item', data: data, type: 'post'}, function (response) {
                $('#btn-confirm-item').show();
                if (response.code === 200) {
                    data.id = response.data;
                    append_item (data);
                } else {
                    $.Alert.error ('code : ' + response.code + '<br/>cause: ' + response.data);
                }
            }, function (response) {
                $.Alert.error ('code: ' + response.code);
            }, close_editor);
        }
    }
    function check_item_edit () {
        var ip = $.trim (ip_addr.val()), mask = $.trim (subnet.val()), name = $.trim (memo.val ()), p = 'auto top';
        if (name === '') {
            show_popover (memo, p, RS(R,'system.config.memo-must'));
            return false;
        }
        if (name.length < 4 || name.length > 10) {
            show_popover (memo, p, RS(R,'system.config.memo-length'));
            return false;
        }
        if (!Libs.ip_pattern().test (ip)) {
        // if (!IP_PATTERN.test (ip)) {
            show_popover (ip_addr, p, RS(R,'system.config.ip-inValid'));
            return false;
        }
        if (!check_mask (mask)) {
            show_popover (subnet, p, RS(R,'system.config.mask-inValid'));
            return false;
        }
        return true;
    }
    function pop_error (c, p, txt) {
        show_popover (c, p, '<span class="text-danger">' + txt + '</span>');
    }
    function check_param_value (c) {
        var type = c.attr ('data-type'), value = $.trim (c.val ()), n, p = 'auto right';
        if (value === '') {
            pop_error (c, p, RS(R,'system.config.param-not-null'));
            return false;
        }
        switch (type) {
            case 'url':
                if (!(/^https?:\/\/.*?$/i).test (value)) {
                    pop_error (c, p, RS(R,'system.config.url-inValid'));
                    return false;
                }
                break;
            case 'int':
            case 'long':
                n = parseInt (value, 10);
                if (isNaN (n) || n.toString () !== value) {
                    pop_error (c, p, RS(R,'system.config.parseInt'));
                    return false;
                }
                break;
            case 'float':
                if (!(/^-?\d+(\.\d+)?$/).test (value)) {
                    pop_error (c, p, RS(R,'system.config.parseFloat'));
                    return false;
                }
                break;
        }

        return true;
    }
    function check_mask (mask) {
        // if (!IP_PATTERN.test (mask)) {
        if (!Libs.ip_pattern ().test (mask)) {
            return false;
        }

        for (var i = 0; i <= 32; i ++) {
            if (mask === MASK[i]) {
                return true;
            }
        }

        return false;
    }
    function show_popover (c, p, content) {
        if (content === '' || content === undefined) {
            content = RS(R,'system.config.error');
        }
        content = '<div class="error-hint">' + content + '</div>';
        c.popover ({html:true,content:content,placement:p}).popover ('show');
        setTimeout (function () {
            c.popover ('destroy');
        }, 2500);
    }
    var mqtt_enable = $('input[name="mqtt.server.enabled"]').on ('change', check_mqtt_status),
        login_type  = $('#cmb-login-limit').on ('change', check_login_items),
        editor      = $('.editor-row'), panel = $('#item-panel'),
        list        = panel.find ('.login-list-items'),
        holder      = $('#editor-holder'),
        ip_addr     = $('#editor-ip-addr'),
        subnet      = $('#editor-subnet'),
        memo        = $('#editor-name');
    check_mqtt_status.apply (mqtt_enable [0]);
    check_login_items.apply (login_type [0]);

    $('#btn-add-item').on ('click', function () {
        editor.appendTo (list);
        editor.find ('input').val ();
        memo.focus ();
    });
    $('.editor-row input').on ('keyup', function (e) {
        if (e.keyCode === 27) { // escape
            cancel_edit ();
        }
    });
    $('#btn-confirm-item').on ('click', accept_edit);
    $('#btn-cancel-item').on ('click', cancel_edit);
    $('.param-list input, .param-list select, input[name="mqtt.server.enabled"]').on ('change', function () {
        var self = $(this), name = self.attr ('name'), value = $.trim (self.val ());
        if (self.is ('input:checkbox')) {
            value = this.checked;
        } else {
            if (!check_param_value (self)) {
                return;
            }
        }
        console.log ('name = ' + name + ', value = ' + value);
        Libs.ajax ({url :'ms/update-config', data: {id: name, value: value}, type: 'post'}, function () {
            var c = self;
            if (self.hasClass ('selectpicker') || self.hasClass ('simple-switch'))
                c = self.parent ();
            show_popover (c, 'auto right', '<span class="text-success">'+RS(R,'system.config.save-success')+'</span>');
        });
    });
    $('.eye').on ('click', function () {
        var self = $(this), p = self.closest ('.sys-param-value').find ('input'), id = p.attr ('name'), icon = self.find ('i');
        if (p.is (':disabled')) {
            return;
        }
        if (icon.hasClass ('fa-eye')) {
            $.Alert.warn(RS(R,'system.config.eye-show'), function () {
                Libs.ajax ({url: 'ms/config-item?id=' + id}, function (response) {
                    response = response.data;
                    p.attr ('type', 'text').prop ('readonly', false).val (response.value).focus ();
                    icon.removeClass ('fa-eye').addClass ('fa-eye-slash');
                });
            });
        } else {
            p.attr ({type:'password',readonly:'readonly'}).val ('');
            icon.removeClass ('fa-eye-slash').addClass ('fa-eye');
        }
    });
});